
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
const PENDING = 'pending'
class Promise {
    constructor(executor) {
        executor(this.resolve, this.reject)
    }
    status = PENDING
    value = null
    reason = null
    onFulFilledCallbacks = []
    onRejectedCallbacks = []
    resolve = (value) => {
        if (this.status == PENDING) {
            this.status = RESOLVED
            this.value = value
        }
        while (this.onFulFilledCallbacks.length) {
            this.onFulFilledCallbacks.shift()(value)
        }

    }
    reject = (reason) => {
        if (this.status == PENDING) {

            this.status = REJECTED
            this.reason = reason
            while (this.onRejectedCallbacks.length) {
                this.onRejectedCallbacks.shift()(reason)
            }
        }
    }
    then = (onFullfilled, onRejected) => {
        const realOnfulfilled = typeof onFullfilled === "function" ? onFullfilled : value => value
        const realOnRejected = typeof onRejected === "function" ? onRejected : reason => { throw reason }
        const promise2 = new Promise((resolve, reject) => {
            const fulfilledMicrotask = () => {
                // 创建一个微任务等待promise2完成初始化
                queueMicrotask(
                    () => {
                        try {
                            const x = realOnRejected(this.value)

                        } catch (error) {
                            reject(error)
                        }
                    }
                )
            }
        })
    }

}


new Promise((resolve, rejected) => {
    resolve()
}).then(() => {

})

Promise.all([f1(), f2(), f3()]).then(([r1, r2, r3]) => { })
[f1(), f2(), f3()].reduce((pre, cur) => { pre.then(cur) }, Promise.resolve())

Promise.resolve().then(f1).then(f2).then(f3)

const applyAsync = (acc, val) => acc.then(val);
const composeAsync = (...funcs) => x => funcs.reduce((pre, cur) => pre.then(cur), Promise.resolve(x))